﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ContactForm.Models;
using Core.Models;
using Microsoft.Web.Helpers;
using System.Reflection;

namespace ContactForm.Controllers
{
    public class FormController : Controller
    {
        //
        // GET: /Form/

        public ActionResult Info()
        {
            string Subject = "";
            string MsgText = "";
            try
            {
                Subject = Request.QueryString["Subject"];
                MsgText = Request.QueryString["MsgText"];
            }
            catch (Exception)
            {
            }
            // Display the error page if the business unit is not authorized to use this plugin
            Guid PluginId = new Guid(((System.Runtime.InteropServices.GuidAttribute)(Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(System.Runtime.InteropServices.GuidAttribute), false)[0])).Value);
            Guid BUId = (Guid)Session["BusinessUnitId"];
            CoreEntities core = new CoreEntities();
            List<Core.Models.BusinessUnitPlugin> BUPlugins = core.BusinessUnitPlugins.Where(m => (m.PluginId == PluginId && m.BusinessUnitId == BUId && m.IsDroppedYN == "N")).ToList();
            if (BUPlugins.Count() < 1) return View("Error");
            if (BUPlugins[0].Plugin.IsDroppedYN == "Y") return View("Error");

            // Great, now that we are authorized, go ahead and display the form.
            ContactFormModel form = new ContactFormModel();
            form.Id = Guid.NewGuid();
            form.OptIn = true;
            form.Subject = Subject;
            form.Message = MsgText;
            Core.Tools.DebugInfo("Contact Form Info: Business Unit Id is " + BUId.ToString());
            form.BusinessUnit = core.BusinessUnits.First(m => m.BusinessUnitId == BUId);
            Core.Tools.DebugInfo("Contact Form Info: Name is " + form.BusinessUnit.BusinessUnitName);
            Core.Tools.DebugInfo("Contact Form Info: Address line 1 is " + form.BusinessUnit.Address.Line1);
            Session["URL"] = "/ContactUs/Form/Info";
            Core.Tools.DebugInfo("Contact Form Info: Loading View");
            Guid AddressId = form.BusinessUnit.Address.AddressId;
            Guid TagId = core.Tags.First(m => (m.TagName == "Main Address" && m.BusinessUnitId == null)).TagId;
            List<Core.Models.BUAddress> addrs = core.BUAddresses.Where(m => (m.BusinessUnitId == BUId && m.TagId == TagId && m.AddressId == AddressId)).ToList();
            Boolean IsPublicAddress = false;
            if(addrs.Count > 0) if(addrs[0].IsPublicYN == "Y") IsPublicAddress = true;
            ViewBag.DisplayAddress = IsPublicAddress;
            return View(form);
        }

        [HttpPost]
        public ActionResult Info(ContactFormModel form)
        {
            CoreEntities core = new CoreEntities();
            Guid BUId = (Guid)Session["BusinessUnitId"];
            ReCaptcha.PrivateKey = Session["ReCaptchaPrivateKey"].ToString();
            if (ReCaptcha.Validate())
            {
                if (!ModelState.IsValid)
                {
                    form.BusinessUnit = core.BusinessUnits.First(m => m.BusinessUnitId == BUId);
                    return View(form);
                }
                List<Contact> contacts = core.Contacts.Where(m => m.Email == form.Email).ToList();
                Guid ContactId;
                if (contacts.Count < 1)
                {
                    Contact c = new Contact();
                    c.ContactId = Guid.NewGuid();
                    c.FirstName = form.FirstName;
                    c.LastName = form.LastName;
                    c.Email = form.Email;
                    c.Status = "L";
                    c.EmailVerifiedYN = "N";
                    c.IsDroppedYN = "N";
                    c.CreatedDT = DateTime.Now;
                    c.CreatedById = Request.IsAuthenticated ? (Guid)Session["UserId"] : Guid.Empty;
                    c.CreatedByName = Request.IsAuthenticated ? Session["UserFullName"].ToString() : "Self Registered";
                    c.ModifiedDT = DateTime.Now;
                    c.ModifiedById = Request.IsAuthenticated ? (Guid)Session["UserId"] : Guid.Empty;
                    c.ModifiedByName = Request.IsAuthenticated ? Session["UserFullName"].ToString() : "Self Registered";
                    ContactBU cbu = new ContactBU();
                    cbu.ContactBusinessUnitId = Guid.NewGuid();
                    cbu.ContactId = c.ContactId;
                    cbu.BusinessUnitId = BUId;
                    cbu.OptIn = form.OptIn ? "Y" : "N";
                    cbu.OptInModifiedDT = DateTime.Now;
                    c.ContactBUs.Add(cbu);
                    core.AddToContacts(c);
                    ContactId = c.ContactId;
                }
                else
                {
                    ContactId = contacts[0].ContactId;
                    if (String.IsNullOrEmpty(contacts[0].LastName)) contacts[0].LastName = form.LastName;
                }
                // Process the OptIn flag if checked for the user. If unchecked the user will have to Opt-out using the profile.
                if (form.OptIn)
                {
                    // Though the contact is found, the contact may not be associated to the current business unit so make sure or add.
                    if (contacts[0].ContactBUs.Where(m => m.BusinessUnitId == BUId).Count() > 0)
                    {
                        ContactBU cbu = contacts[0].ContactBUs.First(m => m.BusinessUnitId == BUId);
                        cbu.OptIn = "Y";
                        cbu.OptInModifiedDT = DateTime.Now;
                    }
                    else
                    {
                        ContactBU cbu = new ContactBU();
                        cbu.ContactBusinessUnitId = Guid.NewGuid();
                        cbu.ContactId = contacts[0].ContactId;
                        cbu.BusinessUnitId = BUId;
                        cbu.OptIn = form.OptIn ? "Y" : "N";
                        cbu.OptInModifiedDT = DateTime.Now;
                        contacts[0].ContactBUs.Add(cbu);
                    }
                }
                Core.Models.Message msg = new Message();
                msg.MessageId = Guid.NewGuid();
                msg.ContactId = ContactId;
                msg.BusinessUnitId = (Guid)Session["BusinessUnitId"];
                msg.Subject = form.Subject;
                msg.MessageText = form.Message.ToString();
                msg.IsDroppedYN = "N";
                msg.CreateDT = DateTime.Now;
                msg.PluginId = new Guid(((System.Runtime.InteropServices.GuidAttribute)(Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(System.Runtime.InteropServices.GuidAttribute), false)[0])).Value);
                msg.ReplyToId = null;
                core.AddToMessages(msg);
                core.SaveChanges();
                Guid DomainId = (Guid)Session["DomainId"];
                List<Core.EmailAddress> To = new List<Core.EmailAddress>();
                To.Add(new Core.EmailAddress("",form.BusinessUnit.Email));
                List<Core.EmailAddress> ReplyTo = new List<Core.EmailAddress>();
                ReplyTo.Add(new Core.EmailAddress(form.FirstName + " " + form.LastName, form.Email));
                bool IsSent = Core.Tools.SendMail(DomainId, form.Subject, form.Message + "<p><br />From: " + form.Email + "</p>", To, null, null, ReplyTo);
                return RedirectToAction("Sent");
            }
            ModelState.Clear();
            form.BusinessUnit = core.BusinessUnits.First(m => m.BusinessUnitId == BUId);
            return View(form);
        }

        //
        // GET: /Form/Sent

        public ActionResult Sent()
        {
            return View();
        }

    }
}
